import {messages} from "share/common";
import React  from "react";
import { Icon, Popover, Popconfirm } from 'antd'
import NodesPanel from './nodes-panel'
import 'styles/components/simple-flow/flow-node.scss'
import { allNodeList, nodeTypes, approverNames, approverTypes } from './node-list'
import { nodeTypeName, chnNumChar} from 'containers/setting/new-workflow/utils'
import SVGIcon from "components/SVGIcon";
import workflowUtil from 'containers/setting/new-workflow/utils'
import { nodeIconImg } from './node-list'
/**
 * 流程图节点，后续可手动添加的节点直接在switch里加就好
 * @param props
 * @return {*}
 * @constructor
 */
function FlowNode(props) {
  const { className = '', nodes, routes, nodeList = [], type, id, onAddNode, onCopyNode, onPasteNode, valueKey,
    onDeleteNode, title, onClick, selected, onChangeNodeLevel, deleteNodes, field, readOnly, currentNodeOID } = props;
  let iconColor, backgroundColor, titleColor;
  let typeClassName = '';
  let sameSpanCondition =[];
  let isShowConfirmObj = {};//是否需要展示 节点插入位置提示
  switch(type) {
    case nodeTypes.APPROVE:
      iconColor = '#50ABFF';
      backgroundColor = '#FFFFFF';
      titleColor = '#363636';
      break;
    case nodeTypes.BOT:
      iconColor = '#50CCD9';
      backgroundColor = '#FFFFFF';
      titleColor = '#363636';
      break;
    case nodeTypes.KNOWN:
      iconColor = '#F7B853';
      backgroundColor = '#FFFFFF';
      titleColor = '#363636';
      break;
    case nodeTypes.PRINT:
      iconColor = '#799FC7';
      backgroundColor = '#73BCFF';
      titleColor = '#FFFFFF';
      break;
    case nodeTypes.AUTOAUDIT:
      iconColor = '#799FC7';
      backgroundColor = '#557DD8';
      titleColor = '#FFFFFF';
      break;
    case nodeTypes.AUDIT:
      iconColor = '#FFA260';
      backgroundColor = '#FFF';
      typeClassName = 'audit';
      break;
    case nodeTypes.CREDIT:
      iconColor = '#B89B6B';
      backgroundColor = '#D6B479';
      titleColor = '#FFFFFF';
      typeClassName = 'credit';
      break;
    case nodeTypes.START:
      typeClassName = 'start';
      break;
    case nodeTypes.END:
      typeClassName = 'end';
      break;
    case nodeTypes.OPEN:
      typeClassName = 'open';
      break;
    case nodeTypes.CLOSE:
      typeClassName = 'close';
      break;
    case nodeTypes.CONDITION:
      typeClassName = 'condition';
      break;
  }

  let renderContent = () => {
    isShowConfirmObj[id] = true;
    let map = {};
    nodes.map(node => {
      map[node[valueKey]] = node;
    });
    routes.map(route => {
      if (route.from === id) {
        if (map[route.to].type === nodeTypes.END || map[route.to].type === nodeTypes.CLOSE) {
          isShowConfirmObj[id] = false;
        }
      }
    })
    if (type === nodeTypes.CONDITION) {
      return (
        <div className="condition">
          <div className="condition-title">
            {!field.ruleConditionDTO && title}<span className="priority">{messages('components.key871',{arg1:field.priority})/*优先级{arg1}*/}</span>
          </div>
          <div className="condition-content">
            {!field.ruleConditionDTO ? messages('components.key872')/*请设置条件内容*/ : (title  || messages('components.key873')/*条件*/) }
          </div>
        </div>
      )
    }
    let nodeType ='';
    if (type === nodeTypes.OPEN || type === nodeTypes.CLOSE) {
      return null;
    } else {
      let showNodeContent = false
      if (type === nodeTypes.APPROVE || type === nodeTypes.KNOWN || type === nodeTypes.AUDIT) {
        showNodeContent = true;
        switch (type){
          case nodeTypes.APPROVE:
            nodeType = messages('components.key876')/*审批*/
            break;
          case nodeTypes.KNOWN:
            nodeType =  messages('components.key875')/*知会*/
            break;
          case nodeTypes.AUDIT:
            nodeType = messages('components.key1043')/*审核*/
            break;
        }
      }
      return (
        <div>
          <div className="node-title" style={{ color: titleColor }}>
            <div className="title-icon" style={{ background: iconColor }}>
              <SVGIcon type={allNodeList.find(node => node.type === type).icon}/>
            </div>
            {title || nodeTypeName[type]}
          </div>
          {
            showNodeContent &&
            <div
              className={`node-content ${!workflowUtil.isHaveApporver(field.ruleBranchApprover) ? 'warning' : (type === nodeTypes.KNOWN ? 'known' : 'default')}`}>
              <div className={`approve-content`}>
                {!workflowUtil.isHaveApporver(field.ruleBranchApprover) ? messages('components.key874')/*请设置节点属性*/ :
                  approverTypes.map(approverType => {
                    if (field.ruleBranchApprover[approverType] && !!field.ruleBranchApprover[approverType].length) {
                      return (
                        <div>
                          <div
                            className="approver-type">{approverNames[approverType]}{type === nodeTypes.KNOWN ? messages('components.key875')/*知会*/ : messages('components.key876')/*审批*/}</div>
                          <div className="approvers">
                            {field.ruleBranchApprover[approverType].map((item, index) => {
                              return (
                                <span>
                                  {item.name}
                                  {(item.containsApportionmentCostCenterManager
                                  || item.containsApportionmentDepartmentManager
                                  || item.containsApportionmentCostCenterPrimaryDepartmentManager) && messages('setting.key1928')/*【含分摊】*/}
                                   {item.level === 1 ? messages('components.key899')/*本级*/ : chnNumChar[item.level - 1]}
                                  {field.ruleBranchApprover[approverType].length !== index + 1 && '、'}
                                </span>
                              )
                            })}
                          </div>
                        </div>
                      )
                    }
                  })
                }
              </div>
            </div>
          }
          {
            type === nodeTypes.BOT &&
            <div className={`ai-content ${field.approvalActions === '8001' ? 'pass' : 'reject'}`}>
              {field.approvalActions === '8001' ? messages('components.key903')/*自动通过*/ : messages('components.key904')/*自动驳回*/}
            </div>
          }
        </div>
      )
    }
  };


  let getConditionlength = () => {
    let tempNodes = JSON.parse(JSON.stringify(nodes));
    let nowNode = tempNodes.find(item => item[valueKey] === id);
    if(nowNode){
      let fromNodeOID = null;
      routes.map(route => {
        if (route.to === nowNode[valueKey]) {
          fromNodeOID = route.from;
        }
      });
      routes.map(route => {
        if (fromNodeOID === route.from) {
          tempNodes.map(node => {
            if (route.to === node[valueKey]) {
              sameSpanCondition.push(node);
            }
          })
        }
      });
    }
    return sameSpanCondition.length;
  };

  let deletedClassNameFlag = deleteNodes.indexOf(id) !== -1 && type !== nodeTypes.OPEN && type !== nodeTypes.CLOSE;
  if (!field.viewMap) {
    field.viewMap = {
      errorToast: 'false',
      isCanPaste: 'false'
    }
  }
  return (
    <div className={`flow-node ${typeClassName}`}>
      {!!allNodeList.length &&
      <div
        className={`flow-node-container ${className} ${selected ? 'selected' : ''} ${field.viewMap.errorToast  === 'true' || field.warning ? 'waring-border' : ''} ${deletedClassNameFlag ? 'delete' : ''}`}
        id={`flow-node-${id}`}
        onClick={onClick}
        style={allNodeList.find(node => node.type === type).manually ? { background: backgroundColor } : {}}
      >
        {!readOnly && (
          type !== nodeTypes.CLOSE && type !== nodeTypes.OPEN &&
          type !== nodeTypes.START && type !== nodeTypes.END
        ) && <div onClick={(e) => e.stopPropagation()}>
          <Popconfirm onConfirm={(e) => {
                        onDeleteNode(id);
                      }}
                      title={messages('components.key900')/*分支下节点将同时删除，是否确认？*/}>
            <Popover placement="top" content={messages('common.delete')/*删除*/}>
              <Icon
                type="close"
                className="close-icon"/>
            </Popover>
          </Popconfirm>
        </div>
        }
        {//跳转已选
          readOnly && selected &&
          <span className="node-selected"><Icon className="selected-icon" type="check"/></span>
        }
        {
          //跳转当前节点
          readOnly && id === currentNodeOID &&
          <span className="node-current">{messages('components.key913')/*当前*/}</span>
        }
        {
          field.viewMap.errorToast === 'true' && (!field.ruleBranchApprover) &&
          <Icon type="exclamation-circle" className="waring-circle"/>
        }
        {

          //优先级
          !readOnly && type === nodeTypes.CONDITION && field.priority !== 1
          && <Icon type="arrow-left"
                   className="left-level-icon"
                   onClick={e => {
                     e.stopPropagation();
                     onChangeNodeLevel('up', id);
                   }}/>
        }
        {
          !readOnly && (type === nodeTypes.CONDITION || type === nodeTypes.APPROVE || type === nodeTypes.KNOWN) &&
          <div className="copy-btn-group" onClick={(e) => e.stopPropagation()}>
            {field.viewMap.isCanPaste === 'true' &&
            <Popconfirm onConfirm={(e) => {
                          e.stopPropagation();
                          onPasteNode(id);
                        }}
                        onVisibleChange={e => {
                          if (!e) {
                          }
                        }}
                        title={messages('components.key878')/*粘贴将覆盖节点内容*/}>
              <Popover placement="top" content={messages('components.key879')/*粘贴*/}>
                <span>
                  <SVGIcon className="copy-btn" type="hly-paste"/>
                </span>
              </Popover>
            </Popconfirm>}
            <span onClick={(e) => {
              e.stopPropagation();
              onCopyNode(field)
            }}> <Popover placement="top" content={messages('common.copy')/*复制*/}>
               <span>
                  <SVGIcon className="copy-btn" type="hly-copy"/>
               </span>
              </Popover></span>
          </div>
        }
        {renderContent()}
        {
          //优先级
          !readOnly && type === nodeTypes.CONDITION && field.priority !== (getConditionlength())
          && <Icon type="arrow-right"
                   className="right-level-icon"
                   onClick={e => {
                     e.stopPropagation();
                     onChangeNodeLevel('down', id);
                   }}/>
        }
      </div>
      }
      {!readOnly && type !== nodeTypes.END && type !== nodeTypes.OPEN && (
        <div className="node-addon">
          <Popover placement="bottom"
                   content={<NodesPanel nodeList={nodeList} onClickNode={node => onAddNode(node, id)}/>}>
            <div className="plus-button">
              <Icon type="plus"/>
            </div>
          </Popover>
          { isShowConfirmObj[id] ?
            <Popconfirm
              onConfirm={(e) => {
                e.stopPropagation();
                onAddNode(nodeTypes.OPEN, id);
              }}
              onCancel={(e) => {
                e.stopPropagation();
                onAddNode(nodeTypes.OPEN, id, 'next');
              }}
              okText={messages('components.key1077')/*主干*/}
              cancelText={messages('components.key913')/*当前*/}
              onVisibleChange={e => {
                if (!e) {
                }
              }}
              placement="right"
              title={messages('components.key1078')/*添加当前分支条件或主干分支条件？*/}>
              <div className="condition-button">
                {messages('components.key905')/*添加条件*/}
              </div>
            </Popconfirm> :
            <div
              onClick={ () => onAddNode(nodeTypes.OPEN, id)}
              className="condition-button">
              {messages('components.key905')/*添加条件*/}
            </div>}
        </div>
      )}
      {!readOnly && type === nodeTypes.OPEN && (
        <div className="node-addon">
          <Popconfirm onConfirm={(e) => {
                        e.stopPropagation();
                        onDeleteNode(id);
                      }}
                      onVisibleChange={e => {
                        if (!e) {
                          onDeleteNode(id, 'OPEN', 'cancel')
                        }
                      }}
                      onCancel={(e) => {
                        e.stopPropagation();
                        onDeleteNode(id, 'OPEN', 'cancel');
                      }}
                      title={messages('components.key880')/*以下节点将全部删除，是否确认删除*/}>
            <div className="delete-button" onClick={ () => onDeleteNode(id, 'OPEN')}>

              <Icon type="arrow-up"/>

            </div>
          </Popconfirm>
          <div className="condition-button" onClick={() => onAddNode(nodeTypes.CONDITION, id)}> {messages('components.key906')/*添加分支*/}
          </div>
        </div>
      )}
    </div>
  )
}

export default FlowNode;
